<template>
  <div class="appointment-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-content">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>预约挂号</h2>
        <div></div>
      </div>
    </div>

    <!-- 医生的信息 -->
    <div v-if="doctor" class="doctor-info">
      <div class="doctor-card">
        <el-avatar :size="60" :src="doctor.avatar">
          {{ doctor.name.charAt(0) }}
        </el-avatar>
        <div class="doctor-details">
          <h3>{{ doctor.name }}</h3>
          <p>{{ doctor.title }}</p>
          <p>{{ doctor.specialty }}</p>
        </div>
      </div>
    </div>

    <!-- 预约表单 -->
    <div class="appointment-form">
      <el-form 
        ref="appointmentFormRef" 
        :model="appointmentForm" 
        :rules="appointmentRules"
        label-width="100px"
      >
        <!-- 选择日期 -->
        <el-form-item label="预约日期" prop="appointmentDate">
          <el-date-picker
            v-model="appointmentForm.appointmentDate"
            type="date"
            placeholder="选择预约日期"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 选择时间段 -->
        <el-form-item label="时间段" prop="appointmentTime">
          <el-radio-group v-model="appointmentForm.appointmentTime">
            <el-radio label="上午">上午 (8:00-12:00)</el-radio>
            <el-radio label="下午">下午 (14:00-18:00)</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 就诊人信息 -->
        <el-form-item label="就诊人姓名" prop="patientName">
          <el-input 
            v-model="appointmentForm.patientName" 
            placeholder="请输入就诊人姓名"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="patientPhone">
          <el-input 
            v-model="appointmentForm.patientPhone" 
            placeholder="请输入联系电话"
          />
        </el-form-item>

        <el-form-item label="身份证号" prop="patientIdCard">
          <el-input 
            v-model="appointmentForm.patientIdCard" 
            placeholder="请输入身份证号"
          />
        </el-form-item>

        <!-- 症状描述 -->
        <el-form-item label="症状描述" prop="symptoms">
          <el-input 
            v-model="appointmentForm.symptoms" 
            type="textarea"
            :rows="4"
            placeholder="请简要描述症状，帮助医生更好地了解病情"
          />
        </el-form-item>

        <!-- 预约须知 -->
        <el-form-item>
          <div class="notice-section">
            <h4>预约须知：</h4>
            <ul>
              <li>请提前15分钟到达医院</li>
              <li>请携带身份证和医保卡</li>
              <li>如需取消预约，请提前24小时联系医院</li>
              <li>预约成功后，医院会发送确认短信</li>
            </ul>
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            class="submit-btn"
            :loading="submitting"
            @click="submitAppointment"
          >
            提交预约
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-skeleton :rows="5" animated />
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { mockAPI } from '../utils/mockData'

export default {
  name: 'Appointment',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const doctor = ref(null)
    const loading = ref(false)
    const submitting = ref(false)
    const appointmentFormRef = ref()

    const doctorId = route.params.doctorId

    // 预约表单
    const appointmentForm = reactive({
      appointmentDate: '',
      appointmentTime: '',
      patientName: '',
      patientPhone: '',
      patientIdCard: '',
      symptoms: ''
    })

    // 表单验证规则
    const appointmentRules = {
      appointmentDate: [
        { required: true, message: '请选择预约日期', trigger: 'change' }
      ],
      appointmentTime: [
        { required: true, message: '请选择时间段', trigger: 'change' }
      ],
      patientName: [
        { required: true, message: '请输入就诊人姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
      ],
      patientPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      patientIdCard: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
      ],
      symptoms: [
        { required: true, message: '请输入症状描述', trigger: 'blur' },
        { min: 10, max: 500, message: '症状描述长度在10到500个字符', trigger: 'blur' }
      ]
    }

    // 获取医生信息
    const loadDoctorInfo = async () => {
      loading.value = true
      try {
        const result = await mockAPI.getDoctorDetail(doctorId)
        if (result.success) {
          doctor.value = result.data
          
          // 获取当前用户信息作为默认值
          const userStr = localStorage.getItem('user')
          if (userStr) {
            const user = JSON.parse(userStr)
            appointmentForm.patientName = user.name
            appointmentForm.patientPhone = user.phone
            appointmentForm.patientIdCard = user.idCard
          }
        }
      } catch (error) {
        ElMessage.error('获取医生信息失败')
        console.error('获取医生信息失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 禁用日期（今天之前的日期）
    const disabledDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7
    }

    // 提交预约
    const submitAppointment = async () => {
      try {
        await appointmentFormRef.value.validate()
        submitting.value = true

        const userStr = localStorage.getItem('user')
        const user = JSON.parse(userStr)

        const appointmentData = {
          userId: user.id,
          doctorId: parseInt(doctorId),
          doctorName: doctor.value.name,
          departmentName: '内科', // 这里可以根据实际情况获取科室名称
          ...appointmentForm
        }

        const result = await mockAPI.createAppointment(appointmentData)
        
        if (result.success) {
          ElMessage.success('预约提交成功！')
          router.push('/my-appointments')
        }
      } catch (error) {
        if (error.message) {
          ElMessage.error(error.message)
        } else {
          ElMessage.error('预约提交失败，请重试')
        }
      } finally {
        submitting.value = false
      }
    }

    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }

    onMounted(() => {
      loadDoctorInfo()
    })

    return {
      doctor,
      loading,
      submitting,
      appointmentForm,
      appointmentFormRef,
      appointmentRules,
      disabledDate,
      submitAppointment,
      goBack
    }
  }
}
</script>

<style scoped>
.appointment-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  color: white;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.back-btn .el-icon {
  margin-right: 5px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}

.doctor-info {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.doctor-card {
  background: white;
  border-radius: 15px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.doctor-details {
  margin-left: 20px;
}

.doctor-details h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
  color: #333;
}

.doctor-details p {
  margin: 0 0 3px 0;
  color: #666;
  font-size: 14px;
}

.appointment-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px 20px;
}

.appointment-form .el-form {
  background: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.notice-section {
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
  margin-top: 20px;
}

.notice-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.notice-section ul {
  margin: 0;
  padding-left: 20px;
  color: #666;
  line-height: 1.6;
}

.notice-section li {
  margin-bottom: 8px;
}

.submit-btn {
  width: 100%;
  height: 50px;
  font-size: 18px;
  border-radius: 25px;
}

.loading {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

@media (max-width: 768px) {
  .appointment-form .el-form {
    padding: 20px;
  }
  
  .doctor-card {
    padding: 15px;
  }
  
  .doctor-details {
    margin-left: 15px;
  }
  
  .notice-section {
    padding: 15px;
  }
}
</style> 